﻿using Dapper;
using ERPEF;
using ERPEF.Model;
using ERPIService;
using ERPService;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.VisualBasic;
using SkiaSharp;
using System.Data;

namespace S4Project.Controllers
{
    [Route("api/[controller]/[action]")]
    [Consumes("application/json")]
    [ApiController]
    public class PurchaseOrderController : ControllerBase
    {
        private readonly MyDbContext myDbContext;
        private readonly pur_Purchase_OrderService _OrderService;
        public PurchaseOrderController(MyDbContext myDbContext, pur_Purchase_OrderService pur_Purchase_OrderService)
        {
            this.myDbContext = myDbContext;
            this._OrderService = pur_Purchase_OrderService;
        }

        //采购订单查询
        [HttpGet]
        public ActionResult<FenYe<pur_Purchase_Order>> OrderFenYe(int currentPage, int pageSize, string where)
        {
            using (var conn = myDbContext.Database.GetDbConnection())
            {
                conn.Open();
                var parameters = new DynamicParameters();
                parameters.Add("pageSize", dbType: DbType.Int32, direction: ParameterDirection.Input, value: pageSize);
                parameters.Add("keyName", dbType: DbType.String, direction: ParameterDirection.Input, value: "ord_id"); // 更改为正确的列名
                parameters.Add("tableName", dbType: DbType.String, direction: ParameterDirection.Input, value: "pur_Purchase_Order"); // 更改为正确的表名
                parameters.Add("currentPage", dbType: DbType.Int32, direction: ParameterDirection.Input, value: currentPage);
                parameters.Add("where", dbType: DbType.String, direction: ParameterDirection.Input, value: where); // 添加 where 参数
                parameters.Add("row", dbType: DbType.Int32, direction: ParameterDirection.Output); // 修改为和存储过程中一致的参数名
                string sql = "[dbo].[FenYe]";
                var result = conn.Query<pur_Purchase_Order>(sql, parameters, commandType: CommandType.StoredProcedure);
                int row = parameters.Get<int>("row");
                FenYe<pur_Purchase_Order> fenye = new FenYe<pur_Purchase_Order>()
                {
                    Order = result,
                    Rows = row,
                };

                if (fenye.Order.Any())
                {
                    return fenye;
                }
                else
                {
                    return Content("没有查到数据");
                }
            }
        }

        //采购订单查询
        [HttpGet]
        public async Task<List<pur_Purchase_Order>> OrderIndex()
        {
            return await _OrderService.OrderQuery();
        }
        //查询供货商
        [HttpGet]
        public async Task<List<bs_vendor>> VenIndex()
        {
            return await _OrderService.VenQuery();
        }

        //采购订单添加
        [HttpPost]
        public async Task<IActionResult> OrderAdd([FromBody] pur_Purchase_Order purchase_Order)
        {
            if (ModelState.IsValid)
            {
                // 查询当前最大编码
                int maxCodeNumber = int.Parse(await GetMaxProductsNumber());

                // 生成新编码
                string newCode = GenerateSaleProducts(maxCodeNumber);

                purchase_Order.ord_number = newCode;

                int res = await _OrderService.OrderAdd(purchase_Order);
                if (res > 0)
                {
                    return Ok("添加成功");
                }
                else
                {
                    return BadRequest("添加失败！");
                }
            }
            else
            {
                return BadRequest(ModelState);
            }
        }
        //产品
        private async Task<string> GetMaxProductsNumber()
        {
            // 从数据库中获取最大的仓库编码数字部分
            string maxProductsString = await myDbContext.pur_Purchase_Order
                .Where(w => w.ord_number.StartsWith("CG"))
                .Select(w => w.ord_number.Substring(10))
                .OrderByDescending(code => code)
                .FirstOrDefaultAsync<string?>();

            // 如果数据库中没有记录或者记录的编码不符合预期格式，则返回 "0001"
            if (string.IsNullOrEmpty(maxProductsString))
            {
                return "1";
            }
            // 解析最大编码的数字部分
            int maxCodeNumber = int.Parse(maxProductsString);
            Console.WriteLine(maxCodeNumber);

            // 生成新的编码数字部分
            int newCodeNumber = maxCodeNumber + 1;

            // 如果新的编码数字部分超过了99，则重置为01
            if (newCodeNumber > 99)
            {
                newCodeNumber = 1;
            }

            return newCodeNumber.ToString();

        }
        // 生成新的编码
        private string GenerateSaleProducts(int codeNumber)
        {
            // 获取当前日期的字符串表示形式，格式为 "yyyyMMdd"
            string dateString = DateTime.Now.ToString("yyyyMMdd");

            // 将数字转换为两位字符串，并在前面补零
            string codeString = codeNumber.ToString("D2");

            // 返回完整的编码，包括前缀 "CG"、日期部分和数字部分
            return "CG" + dateString + codeString;
        }
        //采购订单删除
        [HttpDelete("{ord_id}")]
        public async Task<string> FromDelete(int ord_id)
        {
            var sal = await myDbContext.pur_Purchase_Order
                .Include(m => m.pur_Purchase_From)
                .SingleOrDefaultAsync(m => m.ord_id == ord_id);
            if (sal == null || sal.IsDeleted == true)
            {
                return "未找到对应的数据";
            }
            var undeletedFroms = sal.pur_Purchase_From.Any(f => f.IsDeleted == false);

            if (undeletedFroms)
            {
                return "存在关联数据，删除失败";
            }
            sal.IsDeleted = true;
            await myDbContext.SaveChangesAsync();

            return "删除成功";
        }

        //采购订单修改
        [HttpPut]
        public async Task<IActionResult> OrderUpdate(pur_Purchase_Order purchase_Order)
        {
            if (ModelState.IsValid)
            {
                purchase_Order.pur_Purchase_From = null;
                int res = await _OrderService.OrderUpdate(purchase_Order);
                if (res > 0)
                {

                    return Ok("修改成功！");

                }
                else
                {
                    return BadRequest("修改失败");
                }
            }
            else
            {
                return BadRequest(ModelState);
            }
        }


        //从-采购商品分页查询
        [HttpGet]
        public ActionResult<FenYe<pur_Purchase_From>> FromChanFenYe(int currentPage, int pageSize, string where)
        {
            using (var conn = myDbContext.Database.GetDbConnection())
            {
                conn.Open();
                var parameters = new DynamicParameters();
                parameters.Add("pageSize", dbType: DbType.Int32, direction: ParameterDirection.Input, value: pageSize);
                parameters.Add("keyName", dbType: DbType.String, direction: ParameterDirection.Input, value: "fro_id"); // 更改为正确的列名
                parameters.Add("tableName", dbType: DbType.String, direction: ParameterDirection.Input, value: "pur_Purchase_From"); // 更改为正确的表名
                parameters.Add("currentPage", dbType: DbType.Int32, direction: ParameterDirection.Input, value: currentPage);
                parameters.Add("where", dbType: DbType.String, direction: ParameterDirection.Input, value: where); // 添加 where 参数
                parameters.Add("row", dbType: DbType.Int32, direction: ParameterDirection.Output); // 修改为和存储过程中一致的参数名
                string sql = "[dbo].[FenYe]";
                var result = conn.Query<pur_Purchase_From>(sql, parameters, commandType: CommandType.StoredProcedure);
                int row = parameters.Get<int>("row");
                FenYe<pur_Purchase_From> fenye = new FenYe<pur_Purchase_From>()
                {
                    FromEditUpdate = result,
                    Rows = row,
                };

                if (fenye.FromEditUpdate.Any())
                {
                    return fenye;
                }
                else
                {
                    return Content("没有查到数据");
                }
            }
        }

        //从-添加
        [HttpPost]
        public async Task<IActionResult> FromAdd(pur_Purchase_From PurFrom)
        {
            if (ModelState.IsValid)
            {
                int res = await _OrderService.FromAdd(PurFrom);
                if (res > 0)
                {
                    return Ok("添加成功！");
                }
                else
                {
                    return BadRequest("添加失败！");
                }
            }
            else
            {
                return BadRequest(ModelState);
            }
        }
        //从-修改
        [HttpPut]
        public async Task<IActionResult> FromUpdate(pur_Purchase_From PutFrom)
        {
            if (ModelState.IsValid)
            {
                int res = await _OrderService.FromUpdate(PutFrom);
                if (res > 0)
                {
                    return Ok("修改成功！");
                }
                else
                {
                    return BadRequest("修改失败！");
                }
            }
            else
            {
                return BadRequest(ModelState);
            }
        }

        //从-删除
        [HttpDelete("{fro_id}")]
        public async Task<IActionResult> FromPurDelete(int fro_id)
        {
            int res = await _OrderService.FromDelete(fro_id);
            if (res > 0)
            {
                return Ok("删除成功！");
            }
            else
            {
                return NotFound("删除失败！");
            }
        }


        //采购订单审核
        [HttpPost("{ord_id}")]      
        public async Task<IActionResult> AuditSalesOrder(int ord_id)
        {
            // 从数据库中获取销售订单及其关联的订单详情
            var salesOrder = await myDbContext.pur_Purchase_Order
                .Include(so => so.pur_Purchase_From) // 确保加载关联的订单详情
                .FirstOrDefaultAsync(so => so.ord_id == ord_id);

            // 如果销售订单不存在或已经被逻辑删除，则返回错误信息
            // 检查从表sal_Orders是否有数据
            if (!salesOrder.pur_Purchase_From.Any() || salesOrder.pur_Purchase_From.All(order => order.IsDeleted))
            {
                return BadRequest("从表没有数据，不能进行审核");
            }
            // 检查从表pur_Purchase_From是否有数据
            if (!salesOrder.pur_Purchase_From.Any())
            {
                return BadRequest("从表没有数据，不能进行审核");
            }
            try
            {
                // 审核销售订单
                salesOrder.AuditStatus = true;
                salesOrder.ord_warehouse = '1';
                salesOrder.auditor = "admin"; //审核人
                salesOrder.auditTime = DateTime.Now;//审核时间

                // 创建一个新的销售出库单对象
                var salesOut = new pur_Chase_Receipt
                {
                    pr_id = 0, // 序号
                    pr_number = salesOrder.ord_number, // 订单编号
                    pr_supplier = salesOrder.ord_supplier,//供货商
                    pr_attribute = salesOrder.ord_attribute,//商品属性
                    pr_types = salesOrder.ord_types,//商品种类
                    pr_storage_date=DateTime.Now,//入库时间
                    pr_state=salesOrder.ord_state,//订单状态
                    pr_wareouse=salesOrder.ord_warehouse,//入库状态

                    pr_supplier_company=salesOrder.ord_supplier_company,//供货商名称
                    pr_phone=salesOrder.ord_phone,//手机号
                    pr_supplier_address=salesOrder.ord_supplier_address,//地址

                    out_Return_status=salesOrder.so_Return_status//退货状态
                };

                // 将新的销售出库单添加到数据库
                myDbContext.pur_Chase_Receipt.Add(salesOut);
                // 保存更改到数据库
                await myDbContext.SaveChangesAsync();

                int newOutId = salesOut.pr_id; // 获取自增的pr_id

                // 遍历销售订单从表信息，为每条记录创建销售出库从表对象
                foreach (var order in salesOrder.pur_Purchase_From)
                {
                    var salesOutC = new pur_Chase_From
                    {
                        pf_id = 0, // 序号
                        fro_totale = order.fro_purtotale,//商品属性
                        fro_purname = order.fro_purname,//商品名称
                        orders_unit = order.orders_unit,//单位
                        pf_price = order.fro_puramount,//数量
                        IsDeleted = false,
                        pur_Chase_Receiptpr_id= newOutId,
                    };
                    myDbContext.pur_Chase_From.Add(salesOutC);
                }


                // 保存从表信息
                await myDbContext.SaveChangesAsync();

                return Ok("审核成功，并且已创建对应的采购入库单");
            }
            catch (DbUpdateException ex)
            {
                return StatusCode(500, "审核失败，数据库更新异常：" + ex.Message);
            }
        }
    }
}
